﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using WebStore.Domain.Entities.Enum;
using WebStore.Domain.Entities.Model;
using WebStore.Web.App.Models.Admin;
using WebStore.Web.App.Models.Product;
using WebStore.Web.App.Utility.Attributes;
using WebStore.Web.App.Utility.Enum;
using WebStore.Web.App.Utility.Extensions;
using WebStore.Web.App.Utility.Other;

namespace WebStore.Web.App.Controllers
{
    public partial class AdminController
    {

        [Authorize]
        public ViewResult EditProduct(int? id)
        {
            var model = new EditProductModel();
            if (id != null)
                Mapper.Map<Product, EditProductModel>(_entities.Products.FirstOrDefault(x => x.Id == id), model);

            model.Categories =
                _entities.Categories.ToList().Select(
                    x => new SelectListItem { Text = x.Name, Value = x.Id.ToString(CultureInfo.InvariantCulture) });

            return View(model);
        }

        [HttpPost]
        [ActionName("EditProduct")]
        [Authorize]
        public ActionResult EditProductPost(int? id)
        {
            var model = new EditProductModel();
            if (id != null)
                Mapper.Map<Product, EditProductModel>(_entities.Products.FirstOrDefault(x => x.Id == id), model);

            model.Categories =
                _entities.Categories.ToList().Select(
                    x => new SelectListItem { Text = x.Name, Value = x.Id.ToString(CultureInfo.InvariantCulture) });

            if (!TryUpdateModel(model) || !ModelState.IsValid)
                return View(model);
            string errorMessage;
            if (!_adminService.EditProduct(id,model.Name, model.Description, model.Price, model.CategoryId,model.Photo!=null? model.Photo.ToBytes():null, out errorMessage))
            {
                ModelState.AddModelError("", errorMessage);
                return View(model);
            }
            if(id!=null)
                CreateMessage("Product has been edited", ClientMessageType.Information);
            else
                CreateMessage("Product has been created", ClientMessageType.Information);

            return RedirectToAction("List", "Product");
        }

        public ActionResult DeleteProduct(int id)
        {
            _adminService.DeleteProduct(id);

            return RedirectToAction("List", "Product");
        }
    }
}